import axios from 'axios'
import Vue from 'vue'
import { Toast } from 'vant'
import router from '@/router'
Vue.prototype.$http = axios

const vm = new Vue()
// axios 全局默认配置
const request = axios.create({
  baseURL: '/api',
  timeout: 8000
})
// 设置axios拦截器: 响应拦截器
request.interceptors.request.use(function (config) { // 添加请求头
  // 这里的config包含每次请求的内容
  vm.$showLoading()

  const token = window.localStorage.getItem('auth_token')
  if (token) {
    // 添加headers
    config.headers.Authorization = `${token}`
  } else { }
  return config
}, function (err) {
  vm.$hideLoading()
  return Promise.reject(err)
})

request.interceptors.response.use(function (response) {
  vm.$hideLoading()
  switch (response.data.code) {
    case '401':
      localStorage.removeItem('auth_token')
      Toast.fail('token验证失败(401)')
      return router.replace('/login')
    case '403':
      localStorage.removeItem('auth_token')
      Toast.fail('token过期(403)')
      return router.replace('/login')
    case '404':
      localStorage.removeItem('auth_token')
      Toast.fail('请求出错(404)')
      return router.replace('/login')
    case '500':
      localStorage.removeItem('auth_token')
      Toast.fail('服务器无响应(500)')
      return router.replace('/login')
    default:
      return response
  }
}, function (error) {
  vm.$hideLoading()
  return Promise.reject(error)
})

export default request
